package com.hthy.futures.api;


import com.hthy.futures.AppConfig;
import com.hthy.futures.AppContext;
import com.vilyever.socketclient.SocketClient;
import com.vilyever.socketclient.helper.SocketResponsePacket;
import com.vilyever.socketclient.util.CharsetUtil;

import static com.hthy.futures.AppConfig.REMOTEINT;

/**
 * Author:  Mr.bingley
 * Version:
 * Date:  2017/3/14
 */

public class SocketTradeManager {
    private SocketClient localSocketClient;


    public SocketClient getLocalSocketClient() {
        if (localSocketClient == null) {
            localSocketClient = new SocketClient();
            setupAddress(localSocketClient, AppContext.tradeIp, AppContext.tradePort);
            setupEncoding(localSocketClient);

            // 存在自动断开的bug
            localSocketClient.getHeartBeatHelper().setHeartBeatInterval(1000 * 5);

            localSocketClient.getHeartBeatHelper().setSendString(AppConfig.HEARTORDER);

            // 成功解决一个接收数据因为长度太大导致接收数据有问题
            this.localSocketClient.getSocketPacketHelper().setSegmentLength(4 * 1024);

        }

        return localSocketClient;
    }

    /* Public Methods */
    public void connect(SocketClient socketClient) {
        socketClient.connect();
    }


    /**
     * 设置远程端地址信息
     */
    private void setupAddress(SocketClient socketClient, String remoteIp, int remotePot) {
        socketClient.getAddress().setRemoteIP(remoteIp); // 远程端IP地址
        socketClient.getAddress().setRemotePort(remotePot); // 远程端端口号
        socketClient.getAddress().setConnectionTimeout(1 * 1000); // 连接超时时长，单位毫秒
    }

    /**
     * 设置自动转换String类型到byte[]类型的编码
     * 如未设置（默认为null），将不能使用{@link SocketClient#sendString(String)}发送消息
     * 如设置为非null（如UTF-8），在接受消息时会自动尝试在接收线程（非主线程）将接收的byte[]数据依照编码转换为String，在{@link SocketResponsePacket#getMessage()}读取
     */
    private void setupEncoding(SocketClient socketClient) {
        socketClient.setCharsetName(CharsetUtil.UTF_8); // 设置编码为UTF-8
    }
}
